<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="partyB">
        <el-select
          v-model="queryParams.partyB"
          clearable
          filterable
          placeholder="请选择供供应商"
          class="!w-240px"
          :filter-method="handleSupplierFilterMethod"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:market-contract:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:market-contract:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="乙方名称" align="center" prop="supplierName" min-width="140" />
      <el-table-column
        label="签订时间"
        align="center"
        prop="signingDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="终止日期"
        align="center"
        prop="expirationDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="生效日期"
        align="center"
        prop="effectiveDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="摘要内容" align="center" prop="contractSummary" />
      <el-table-column label="合同责任人" align="center" prop="contractPerson" width="100" />
      <el-table-column label="文件" align="center" prop="contractFile" width="140">
        <template #default="scope">
          <!-- 预览弹出框 -->
          <el-popover
            :visible="visiblePreview[scope.row.id]"
            placement="top"
            ref="previewPopovers"
            :ref-key="`preview-${scope.row.id}`"
            @hide="() => (visiblePreview[scope.row.id] = false)"
          >
            <div
              v-for="(item, index) in scope.row.contractFile"
              :key="item"
              style="display: flex; align-items: center"
            >
              <el-button link type="primary" @click="previewHandler(item, scope.row.id)">
                预览文件{{ index + 1 }}
              </el-button>
            </div>
            <template #reference>
              <el-button
                link
                type="primary"
                @click.stop="togglePreview(scope.row.id)"
                ref="previewButtons"
                :ref-key="`preview-btn-${scope.row.id}`"
              >
                在线预览
              </el-button>
            </template>
          </el-popover>

          <!-- 下载弹出框 -->
          <el-popover
            :visible="visibleDownload[scope.row.id]"
            placement="top"
            ref="downloadPopovers"
            :ref-key="`download-${scope.row.id}`"
            @hide="() => (visibleDownload[scope.row.id] = false)"
          >
            <div
              v-for="(item, index) in scope.row.contractFile"
              :key="item"
              style="display: flex; align-items: center"
            >
              <el-button link type="primary" @click="downloadHandler(item, scope.row.id)">
                下载文件{{ index + 1 }}
              </el-button>
            </div>
            <template #reference>
              <el-button
                link
                type="primary"
                @click.stop="toggleDownload(scope.row.id)"
                ref="downloadButtons"
                :ref-key="`download-btn-${scope.row.id}`"
              >
                下载
              </el-button>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="版本备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:market-contract:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:market-contract:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MarketContractForm ref="formRef" @success="getList" />

  <!-- 预览弹框 -->
  <Dialog v-model="previewDialogVisible" title="预览" width="700">
    <div class="flex justify-around">
      <IFrame :src="previewUrl" />
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MarketContractApi, MarketContractVO } from '@/api/erp/marketcontract'
import MarketContractForm from './MarketContractForm.vue'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'

/** 市场管理合同信息 列表 */
defineOptions({ name: 'ErpMarketContract' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const supplierList = ref<SupplierVO[]>([]) // 供应商列表

const loading = ref(true) // 列表的加载中
const list = ref<MarketContractVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractName: undefined,
  contractNo: undefined,
  partyB: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MarketContractApi.getMarketContractPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MarketContractApi.deleteMarketContract(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MarketContractApi.exportMarketContract(queryParams)
    download.excel(data, '市场管理合同信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 存储每行的预览弹出框状态
const visiblePreview = ref({})
// 存储每行的下载弹出框状态
const visibleDownload = ref({})

// 弹出框和按钮的ref引用
const previewPopovers = ref({})
const previewButtons = ref({})
const downloadPopovers = ref({})
const downloadButtons = ref({})

/** 在线预览相关 */
const previewDialogVisible = ref(false)
const previewUrl = ref('')

// 切换预览弹出框显示状态
const togglePreview = (rowId) => {
  // 先关闭所有弹出框
  closeAllPopovers()
  // 再打开当前行的预览弹出框
  visiblePreview.value[rowId] = true
}

const previewHandler = (url, rowId) => {
  visiblePreview.value[rowId] = false
  const previewPath = url.replace('/get/', '/preview/')
  previewUrl.value = previewPath
  previewDialogVisible.value = true
}

/** 下载相关 */
const downloadHandler = (url, rowId) => {
  visibleDownload.value[rowId] = false
  window.open(url, '_self')
}

// 切换下载弹出框显示状态
const toggleDownload = (rowId) => {
  // 先关闭所有弹出框
  closeAllPopovers()
  // 再打开当前行的下载弹出框
  visibleDownload.value[rowId] = true
}

/** 关闭所有弹出框 */
const closeAllPopovers = () => {
  // 关闭所有预览弹出框
  Object.keys(visiblePreview.value).forEach((key) => {
    visiblePreview.value[key] = false
  })
  // 关闭所有下载弹出框
  Object.keys(visibleDownload.value).forEach((key) => {
    visibleDownload.value[key] = false
  })
}

/** 点击其他区域关闭弹出框 */
const handleClickOutside = (e) => {
  // 检查点击是否在预览弹出框或按钮内部
  const isPreviewRelated =
    Object.values(previewPopovers.value).some((popover) => {
      return popover?.$el?.contains(e.target)
    }) ||
    Object.values(previewButtons.value).some((button) => {
      return button?.$el?.contains(e.target)
    })

  // 检查点击是否在下载弹出框或按钮内部
  const isDownloadRelated =
    Object.values(downloadPopovers.value).some((popover) => {
      return popover?.$el?.contains(e.target)
    }) ||
    Object.values(downloadButtons.value).some((button) => {
      return button?.$el?.contains(e.target)
    })

  // 如果点击在所有弹出框和按钮外部，则关闭所有弹出框
  if (!isPreviewRelated && !isDownloadRelated) {
    closeAllPopovers()
  }
}

const handleSupplierFilterMethod = async (query?: string) => {
  console.log('filtering with query:', query)
  const data = await SupplierApi.getSupplierSimpleList()
  if (!query) {
    supplierList.value = data.slice(0, 200)
    return supplierList.value
  }
  supplierList.value = data.filter((d) => d.name.toLowerCase().includes(query.toLowerCase()))
  return supplierList.value
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  document.addEventListener('click', handleClickOutside)
  handleSupplierFilterMethod()
  // supplierList.value = await SupplierApi.getSupplierSimpleList()
})

// 卸载时移除事件监听
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>
